
local events = {}
local handlers = {}
local money = 0

-------------------------------------------------------------------------------
function Spy.RefreshMoneyFrame()
   local f = SpyMoneyFrame
   if f then
      f.gained:SetText(Spy.GetMoneyString(SpyCharDB.MoneyStats.gained).."   ")
      f.lost:SetText(Spy.GetMoneyString(SpyCharDB.MoneyStats.lost).."   ")
   end
end

function events:PLAYER_MONEY()
   local cur = GetMoney()
   local dif = cur - money
   local moneyStr = Spy.GetMoneyString(abs(dif))
   local stats = SpyCharDB.MoneyStats
      
   if dif > 0 then
      moneyStr = "+ " .. moneyStr
      stats.gained = stats.gained + dif
   elseif dif < 0 then
      moneyStr = "- " .. moneyStr
      stats.lost = stats.lost + abs(dif)
   end
   
   Spy.RefreshMoneyFrame()
   
   if SpySCT then
      local text = Spy.GetMoneyStringColored(dif, true)
      if dif > 0 then
         SpySCT.ScrollText('GOLD', text, {1, 1, 1}, nil, Font'CalibriB', 16)
      elseif dif < 0 then
         SpySCT.ScrollText('GOLD', text, {1, 0, 0}, nil, Font'Calibri', 16)
      end
   end

   money = cur
end

function events:PLAYER_ENTERING_WORLD()
   money = GetMoney()
end

function Spy.InitMoneyFrame()
   if not SpyDB.bNoMoneyFrame then
      local f = SpyTextList.Create("SpyMoneyFrame", UIParent, "NumberFontNormalSmall")
      f.justifyH = "RIGHT"
      f.offsetX = 10
      f.gained = f:CreateEntry("gained", {1, 1, 1}, {0, 0, 0, 0})
      f.lost = f:CreateEntry("lost", {1, 0, 0}, {0, 0, 0, 0})
      Spy.RefreshMoneyFrame()
      f:SetWidth(120)
      
      local function ResetStats()
         SpyCharDB.MoneyStats.gained = 0
         SpyCharDB.MoneyStats.lost = 0
         Spy.RefreshMoneyFrame()
      end
      
      f.resetButton = Spy.CreateButton('x', ResetStats, f)
      f.resetButton:SetPoint('LEFT', f, 'RIGHT')
   end
end

-- fixme
-- Spy.AddStartupFunc(Spy.InitMoneyFrame)

-------------------------------------------------------------------------------
-- local TimeCounter = 0.0
-- function handlers.OnUpdate(self,elapsed)
   -- if Spy.bLoaded then
      -- TimeCounter = TimeCounter + elapsed
      -- if TimeCounter >= SpyDB.ResetCPUUsageFreq then
         -- ResetCPUUsage()
         -- TimeCounter = 0.0
      -- end
   -- end
-- end

-------------------------------------------------------------------------------
local frame = CreateFrame("FRAME") -- Need a frame to respond to events
Spy.RegisterAll(frame, events, handlers)

-------------------------------------------------------------------------------
SLASH_SPYHUD1 = "/spyhud"
SLASH_SPYHUD2 = "/spy"

function SlashCmdList.SPYHUD(msg)
   print("Spy slash command handler: "..msg)
   if msg == "mana" then
      Toggle(SpyMana)
   elseif msg == "cd" then
      Toggle(SpyCooldown_Long)
   elseif msg == "money" or msg == "$" then
      Toggle(SpyMoneyFrame)
   end
end

